import Vue from "vue";
import {getSceneDataAPI} from "../../server";
import type MasBrowserType from "../types/masBrowser";

interface GisMapDataType {
  /** bind **/
  engineLoading: boolean,
  engineReady: boolean,
  emptyDescription: string,
  /** unbind **/
  engine?: MasBrowserType,
}

interface GisMapMethodType {
  loadScene(): Promise<void>,

  sceneReady(): void,

  closePopup(): void
}

interface GisMapPropType {
  sceneID: string,
}

export interface GisMapProvideType {
  getEngine(): MasBrowserType,

  closePopup(): void
}

//经过测试发现如果engine没有挂到data里面，后面通过方法挂载到实例上，那么它不会被深度追踪。
//并且这个没有被深度追踪的engine，通过Prop的方法传递到子组件后，同样不会被被追踪。
//比较推荐provide的形式注入一个getEngine的方法，这样所有子组件都可以inject这个方法

export default Vue.extend<GisMapDataType, GisMapMethodType, unknown, GisMapPropType>({
  name: 'GisMap',
  data() {
    return {
      engineLoading: true,
      engineReady: false,
      emptyDescription: ''
    }
  },
  provide() {
    return {
      getEngine: () => this.engine as MasBrowserType,
      closePopup: this.closePopup,
    } as GisMapProvideType
  },
  props: {
    sceneID: {
      type: String,
      required: true,
      default: ''
    }
  },
  mounted() {
    this.loadScene();
  },
  methods: {
    //加载场景
    async loadScene() {
      if (!this.sceneID) {
        this.emptyDescription = '场景ID未定义，无法加载场景';
        this.engineLoading = false;
        return;
      }
      const sceneData = await getSceneDataAPI(this.sceneID);
      if (!sceneData) {
        this.emptyDescription = `场景加载失败，请确认ID为 ${this.sceneID} 的场景是否存在`;
        this.engineLoading = false;
        return;
      }
      try {
        const engine = new MasBrowser(sceneData, 'mapContainer');
        engine.addEventListener('sceneLoaded', this.sceneReady);
        engine.addEventListener('mapClick', this.closePopup)
        engine.sceneDataInit();
        this.engine = engine;
      } catch (e) {
        console.log(e);
        this.emptyDescription = '场景加载失败，详情见控制台';
        this.engineLoading = false;
        return;
      }
    },
    //场景就绪
    sceneReady() {
      this.engineReady = true;
      this.engineLoading = false;
    },
    //关闭气泡弹窗
    closePopup() {
      this.engine?.hideUniquePopup();
    }
  }
})
